<template>
  <view class="grzq-center">
    <scroll-view scroll-y="true" enable-pull-down-refresh="true" @refresh="onRefresh">
      <view class="grzq-home">
        <view class="banner">
          <swiper class="banner-swiper" circular autoplay>
            <swiper-item v-for="(item, index) in swiperConfig" :key="index">
              <image class="banner-image" :src="item.banner_cover" mode="aspectFill" />
            </swiper-item>
          </swiper>
        </view>

        <!-- 会员卡信息 -->
        <view class="card" v-if="bindStatus === '1'">
          <view class="card-info h163 flex h130">
            <view class="card-img h120 w100 mt10">
              <image class="w97 h97" :src="cardImg" />
            </view>
            <view class="card-header  pb20 pl20">
              <view class="card-title">会员水卡</view>
              <view class="card-number">卡号：{{ card_list.card_code || '-' }}</view>
            </view>
            <view class="card-body   fs20  flex">
              <view class="balance-info ar pt10 pr10 pb10">
                <view class="balance-label">当前余额</view>
                <view class="balance-label pb1">有效期至</view>
                <view class="hr"></view>
                <view class="balance-label pb2">时效套餐余额</view>
                <view class="balance-label">时效有效期</view>
              </view>
              <view class="info-item fs20 pt10 pb10 af">
                <view class="info-value blue">{{ card_list.remaining_value || 0 }}元</view>
                <view class="info-value pb1">{{ card_list.updated_time ? card_list.updated_time.substr(0, 10) : '-' }}
                </view>
                <view class="info-value blue pb2">{{ card_list.remaining_value || 0 }}元</view>
                <view class="info-value">{{ card_list.updated_time ? card_list.updated_time.substr(0, 10) : '-' }}
                </view>
              </view>
            </view>
          </view>
          <view class="card-tel flex pl10 pr10">
            <view class="info-tel w-40 flex">
              <view class="info-label">绑定电话：</view>
              <view class="info-value"> {{ card_list.user_info.mobile || '-' }}</view>
            </view>
            <view class="info-item w-60 ">
              绑定社区： {{ card_list.apparatus_info.title || '-' }}
            </view>
          </view>
        </view>
        <view class="card_empty ac  mb20 " v-else>
          <view>您还没有绑定实体卡哦~</view>
          <view class="pt10 bindBtn" @click="bindingCardClick">前往绑定</view>
        </view>

        <view class="function-grid">
          <view class="grid-item" v-for="(item, index) in menuConfig" :key="index" @click="menuConfigClick(item)">
            <view class="grid-icon">
              <image :src="item.img" class="slide-image" mode="widthFix"></image>
            </view>
            <view class="grid-text ac">{{ item.text }}</view>
          </view>
        </view>
        <view class="bottom-toolbar flex pb150">
          <view class="toolbar-map flex left" @click="deviceClick">
            <view class="map-lat h150 w150">
              <image :src="mapImg" />
            </view>
            <view class="toolbar-text ">附近设备</view>
          </view>
          <view class="toolbar-item flex">
            <view class="toolbar-img " @click="openH5">
              <image :src="phoneImg" />
              <view>客服电话</view>
            </view>
            <view class="toolbar-img  w5 w-100">
              <image class="toolbar-hr" :src="tImg" />
            </view>
            <view class="toolbar-img " @click="openVideo">
              <image class="video" :src="videoImg" />
              <view>视频通话</view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    <myTabbar :jumpType="currentIndex"></myTabbar>
  </view>

</template>

<script>
import { onPullDownRefresh } from "@dcloudio/uni-app";
import myTabbar from '@/components/tabBar/myTabbar.vue'
import { mapGetters } from 'vuex';
import { getBanners } from "@/api/system";
import { checkCard, getEquipmentPlan, addWaterList, saveInnerCard, saveInnerCardNew,saveWxPay, getEquipmentOnline, deleteCard } from '@/api/water';
// import { rechargeOrderAdd } from "@/api/user/recharge";
export default {

  components: {
    myTabbar
  },
  data() {
    return {
      currentIndex: 'dashui',
      card_list: {},
      bindStatus: '0',
      card_show: false,

      toolbarList: [
        { name: '附近设备', icon: 'location' },
        { name: '联系客服', icon: 'phone' },
        { name: '在线视频', icon: 'video' }
      ],
      indicatorDots: false,
      circular: true,
      autoplay: true,
      interval: 2500,
      duration: 500,
      swiperCur: 0,
      imgUrls: [],
      imgConfig: [],
      swiperConfig: [
      ],
      docConfig: 1,
      itemEdge: 1,
      lrConfig: 1,
      mbConfig: 1,
      tabConfig: 1,
      mapImg: this.$common.imgUrl() + '/images/home/positioning@2x.png',
      phoneImg: this.$common.imgUrl() + '/images/home/phone@2x.png',
      tImg: this.$common.imgUrl() + '/images/home/t@2x.png',
      videoImg: this.$common.imgUrl() + '/images/home/video@2x.png',
      cardImg: this.$common.imgUrl() + '/images/home/card@2x.png',
      menuConfig: [],
      openid: '',
      optionsNew: '',
      payStatus: false,
      feeId: 0,
      checkOnlineStatus: false,
      equipment_id:''
    }
  },
  async onLoad(options) {
    this.optionsNew = decodeURIComponent(options.q)
    this.getBannerList()
    if (this.optionsNew != 'undefined') {
      this.initWaterCard()
    }
    // 删除
    // deleteCard({ card_no: '25010102165'}).then(res => {})
  },
  created() {
    this.openid = JSON.parse(uni.getStorageSync('USER_INFO')).openid
    const basicConfig = uni.getStorageSync('BASIC_CONFIG');
    this.menuConfig = basicConfig.menu_config
  },
  onShow() {
    if (this.optionsNew === 'undefined') {
      this.initWaterCardAgin()
    }
  },
  methods: {
    // 刷新备用
    initWaterCardAgin() {
      checkCard({})
        .then(res => {
          if (res.data.data.length != 0) {
            this.bindStatus = '1'
            if (res.data.data.length === 1) {
              this.card_list = res.data.data[0]
            } else {
              this.cardList = res.data.data
              res.data.data.map(e => {
                if (e.is_default === 0) {
                  this.card_list = e
                }
              })
            }
          } else {
            this.bindStatus = '0'
          }
        })
        .catch(res => {
        });
    },
    initWaterCard() {
      checkCard({})
        .then(res => {
          if (res.data.data.length != 0) {
            this.bindStatus = '1'
            if (res.data.data.length === 1) {
              this.card_list = res.data.data[0]
            } else {
              this.cardList = res.data.data
              res.data.data.map(e => {
                if (e.is_default === 0) {
                  this.card_list = e
                }
              })
            }
          } else {
            this.bindStatus = '0'
          }
          // 等卡内余额查询以后再扫码回调
          if (this.optionsNew != 'undefined') {
            this.wxScan(this.optionsNew)
          }
        })
        .catch(res => {
        });
    },
    getBannerList() {
      getBanners().then(res => {
        this.swiperConfig = res.data;
        console.log(this.swiperConfig)
      })
    },
    openH5() {
      const phoneNumber = '0531-84231239';
      uni.makePhoneCall({
        phoneNumber: phoneNumber, // 电话号码
        success: function () {
          console.log('拨打电话成功！');
        },
        fail: function (err) {
          console.log('拨打电话失败：', err);
        }
      });
    },
    openVideo() {
      uni.showToast({
        title: '暂未开放！',
        icon: 'none'
      });
    },
    // 点击分类
    menuConfigClick(row) {
      const url = row.url;
      if (row.url === '/pages/intake/scan/index') {
        // 扫码打水
        this.scanFun()
      } else if (row.url === '/pages/intake/recharge/package' || row.url === '/pages/intake/device/repair' || row.url === '/pages/intake/feedback/index' || row.url === '/pages/intake/recharge/record') {
        if (this.bindStatus === '0' && row.url === '/pages/intake/recharge/package') {
          uni.showToast({
            title: '暂无水卡，请先绑定水卡',
            icon: 'none'
          });
        } else {
          this.$common.navTo(url);
        }
      } else {
        uni.showToast({
          title: '暂未开放！',
          icon: 'none'
        });
        // this.$common.navTo(url);
      }
    },
    wxScan(e) {
      this.result = e; // 获取扫码结果
      if (this.result) {
        const obj = this.GetWxMiniProgramUrlParam(this.result)
        // 第二步调用
        this.getEquipmentInfo(obj)
      } else {
        uni.showToast({
          title: '扫码失败'
        })
      }
    },
    scanFun() {
      // 1.进来扫码识别 是此域名开头next 否则提示
      // 2.分析地址参数 或者设备id && 设备端口查询详情获取具体金额 生成订单
      // 3.详情信息+卡号和金额，判断卡内余额是否大于当前详情金额
      // 4.当前余额大于详情余额 调取账号支付 否则微信支付
      uni.scanCode({
        success: (res) => {
          this.result = res.result; // 获取扫码结果
          if (this.result.split('/api/')[0] === 'https://grzqwx.wajx.top' || this.result.split('/api/')[0] === 'https://grzq.wajx.top' || this.result.split('/api/')[0] === 'https://wxopen.grzq.xyz') {
            console.log('扫码结果:', this.result);
            const obj = this.GetWxMiniProgramUrlParam(this.result)
            // 第二步调用
            this.getEquipmentInfo(obj)
          } else {
            uni.showToast({
              title: '扫码失败'
            })
          }
        },
        fail: (err) => {
          console.error('扫码失败:', err);
        }
      });
    },
    // 第二步详情  查询机器详情信息
    getEquipmentInfo(e) {
      getEquipmentPlan({ eid: e.eid, type: e.type, openid: this.openid }).then(res => {
        this.equipment_id =  res.data.equipment_id
        this.payStatus = parseFloat(this.card_list.remaining_value) > res.data.money ? true : false
        this.feeId = res.data.id
        this.checkOnline(this.feeId)
      })
    },
    // 检测设备状态
    checkOnline(feeId) {
      uni.showLoading({
        title: '设备连接中...'
      });
      getEquipmentOnline({ fee_id: feeId }).then(res => {
        this.checkOnlineStatus = res.data.check
        if (res.data.check === true) {
        
          this.addOrder()
        } else {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(() => {
            uni.hideLoading();
          }, 5000)
        }
      })
    },

    // 创建订单
    addOrder() {
    // 如果是卡内足够 走ic支付 微信走创建订单--
      if (this.payStatus === true) {
        this.saveCardPayNew()
      }else{
        addWaterList({
          openid: this.openid,
          type: 'consume',
          fee_id: this.feeId,
          card_no: this.card_list.card_code,
          pay_type: this.payStatus === true ? 'online_card' : 'success_wx'
        }).then(resWater => {
          if(resWater.status === 0){
            this.saveWxPayFun(resWater.data.data.order_sn)
            // 支付方式  code === 100卡内 2
            // if (payStatus === true && resWater.data.code === 100) {
            //   // this.saveCardPay()
            //   uni.showLoading({
            //     title: '正在打水中...'
            //   });
            //   setTimeout(() => {
            //     uni.hideLoading();
            //     this.$common.navTo("/pages/index/success")
            //   }, 2000)
            // } else {
            //   this.saveWxPayFun(resWater.data.data.order_sn)
            // }
          }
        }).catch(error => {
          console.log('错误信息', error)
          uni.showToast({
            title: '设备已离线，请联系客服人员',
            icon: 'none'
          });
        });
      }
    },
    // 卡内支付
    // saveCardPay() {
    //   // order_sn: orderSn,
    //   saveInnerCard({ openid: this.openid, pay_type: 'online_card' }).then(res => {
    //     if (res.status === 0) {
    //       uni.showLoading({
    //         title: '正在打水中...'
    //       });
    //       setTimeout(() => {
    //         uni.hideLoading();
    //         this.$common.navTo("/pages/index/success")
    //       }, 2000)
    //     } else {
    //       uni.showToast({
    //         title: res.message,
    //         icon: 'none'
    //       });
    //     }
    //   })
    // },
     // 卡内支付New
    saveCardPayNew() {
      // order_sn: orderSn,
      saveInnerCardNew({ card_no:  this.card_list.card_code, equipment_id: this.equipment_id }).then(res => {
        if (res.status === 0) {
          uni.showLoading({
            title: '正在打水中...'
          });
          setTimeout(() => {
            uni.hideLoading();
            this.$common.navTo("/pages/index/success")
          }, 2000)
        } else {
          uni.showToast({
            title: res.message,
            icon: 'none'
          });
        }
      })
    },
    // 微信支付
    saveWxPayFun(orderSn) {
      const openid = this.openid
      saveWxPay({ openid: this.openid, order_sn: orderSn }).then(res => {
        const { data } = res
        uni.hideLoading();
        uni.requestPayment({
          provider: "wxpay",
          timeStamp: data.timeStamp, // 时间戳，从 1970 年 1 月 1 日 00:00:00 至今的秒数
          nonceStr: data.nonceStr, // 随机字符串，不长于 32 位
          package: data.package, // 统一下单接口返回的 prepay_id 参数值，格式如：prepay_id=xxx
          signType: 'RSA', // 签名类型，默认为 'MD5'，支持 'HMAC-SHA256'
          paySign: data.paySign, // 签名，具体签名生成方式见微信支付文档
          success: function (res) {
            uni.showLoading({
              title: '正在打水中...'
            });
            setTimeout(() => {
              uni.hideLoading();
              uni.reLaunch({
                url: '/pages/index/success'
              });
            }, 2000)
            // 开始打水取消
            // saveInnerCard({ openid: openid, order_sn: orderSn, pay_type: 'success_wx' }).then(resInner => {
            //   if (resInner.status === 0) {
            //     uni.showLoading({
            //       title: '正在打水中...'
            //     });
            //     setTimeout(() => {
            //       uni.hideLoading();
            //       uni.reLaunch({
            //         url: '/pages/index/success'
            //       });
            //     }, 2000)
            //   } else {
            //     uni.showToast({
            //       title: resInner.message,
            //       icon: 'none'
            //     });
            //   }
            // })
          },
          fail: function (err) {
            console.log('支付失败', err);
          }
        });
      }).catch(error => {
          console.log('错误信息', error)
          uni.showToast({
            title: '支付失败',
            icon: 'none'
          });
        });
    },
    // 处理参数
    GetWxMiniProgramUrlParam(options) {
      let theRequest = {};
      if (options.indexOf("#") != -1) {
        const str = options.split("#")[1];
        const strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
      } else if (options.indexOf("?") != -1) {
        const str = options.split("?")[1];
        const strs = str.split("&");
        for (let i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
      }
      return theRequest;
    },
    bindingCardClick(row) {
      this.$common.navTo('/pages/intake/card/bind_card');
    },
    deviceClick() {
      this.$common.navTo('/pages/intake/device/index');
    },
    callPhone() {
      let BASIC_CONFIG = this.$Cache.get('BASIC_CONFIG');
      let tel = BASIC_CONFIG['station_open'] ?? "0531-84231239"

      //#ifdef MP-WEIXIN
      uni.makePhoneCall({
        phoneNumber: tel
      });
      //#endif
      //#ifdef APP-PLUS
      plus.device.dial(tel, true);
      //#endif
    },
    // swiper
    swiperChange(e) {
      this.imgUrls = e.detail.current
    },
    //替换安全域名
    setDomain: function (url) {
      url = url ? url.toString() : '';
      //本地调试打开,生产请注销
      if (url.indexOf("https://") > -1) return url;
      else return url.replace('http://', 'https://');
    },
  },
  // watch: {
  //   checkOnlineStatus: {
  //     handler(val) {
  //       if (val === true) {
  //         this.addOrder()
  //       } else {
  //         this.checkOnline()
  //       }
  //     },
  //     // immediate: true,
  //     deep: true
  //   },
  // },
}
</script>

<style lang="scss">
.grzq-center {
  overflow: auto;
  background: url($baseUrl + '/images/bg/home_bg@2x.png') no-repeat center / 100% 100%;
  width: 100%;
  height: calc(100vh - 140rpx);
  justify-content: center;
  background-size: cover;
  /* 使背景图片覆盖整个元素 */
  padding: 120rpx 30rpx 30rpx 30rpx;

  .grzq-home {
    .banner {
      margin: 20rpx 0;
      border-radius: 16rpx;
      overflow: hidden;

      .banner-swiper {
        width: 100%;
        height: 447rpx;

        .banner-image {
          width: 100%;
          height: 100%;
        }
      }

    }

    .card {
      //border: solid;
      background: url($baseUrl + '/images/bg/card@2x.png') no-repeat center/100% 100%;
      border-radius: 20rpx;
      margin-bottom: 30rpx;
      height: 211rpx;
      padding: 0rpx 29rpx;

      .card-img {
        padding-top: 26rpx;

        image {
          width: 97rpx;
          height: 97rpx;
        }
      }

      .card-header {
        width: 290rpx;
        padding-top: 40rpx;

        .card-title {
          font-weight: 550;
          font-size: 38rpx;
          color: #212B3D;
        }

        .card-number {
          font-size: 25rpx;
          color: #86909C;
        }

      }

      .card-body {
        flex: auto;
        margin-top: 10rpx;

        //flex-direction: column; /* 垂直布局 */
        .balance-info {
          position: relative;
          justify-content: center;
          /* 垂直居中 */
          align-items: flex-start;
          /* 水平靠左对齐 */
        }

        .card-item {
          justify-content: center;
          /* 垂直居中 */
          align-items: flex-start;
          /* 左侧信息靠左对齐，右侧信息默认对齐 */
          flex-wrap: wrap;
          /* 允许换行 */
        }

        .blue {
          color: #034EFD;
          font-size: 21rpx;
        }

        .hr {
          padding: 14rpx 0;
          position: absolute;
          width: 240rpx;
          border-top: dashed 1px #ccc;
        }

        .pb1 {
          margin-bottom: 10rpx;
        }

        .pb2 {
          padding-top: 10rpx;
        }
      }

      .card-tel {
        align-items: flex-end;
        color: #86909C;
        font-size: 21rpx;
        margin-top: 7rpx;

        .info-item {
          text-align: right;
        }
      }

      .card_bd {
        .card-info {
          padding: 10rpx;

          /* 可选，添加内边距 */
          .card-img,
          .card-header,
          .card-body {
            justify-content: center;
            //border: solid;
          }

          .card-img {
            width: 120rpx;
          }

          .card-header {
            width: 300rpx;

            .card-title {
              font-size: 16px;
              display: block;
            }

          }


        }

        .card-tel {
          border: solid;
          align-items: flex-end;

          .info-tel {}

          .info-item {}
        }
      }

      .card_falst {
        .tip {}
      }
    }

    .card_empty {
      background: url($baseUrl + '/images/home/card_bg@2x.png') no-repeat center/100% 100%;
      height: 211rpx;
      padding: 64rpx 0;
      border-radius: 15rpx;
    }

    .bindBtn {
      width: 166rpx;
      height: 43rpx;
      line-height: 26rpx;
      background-color: #034EFD;
      color: #fff;
      border-radius: 20rpx;
      text-align: center;
      margin: 34rpx auto;
      font-size: 21rpx;
    }

    .function-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 20rpx;
      background-color: #FFFFFF;
      border-radius: 20rpx;
      padding: 30rpx;
      margin-bottom: 30rpx;

      .grid-item {
        background-color: #efefef;
        width: 141rpx;
        height: 192rpx;
        border-radius: 12rpx;
        padding: 36rpx 0;

        .grid-icon {
          height: 48px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 8rpx;

          image {
            width: 75rpx;
            height: 76rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }

        .grid-text {
          font-size: 25rpx;
        }
      }
    }

    .bottom-toolbar {
      //border: solid;
      display: flex;
      // background-color: #ffffff;
      border-radius: 20rpx;
      font-size: 22rpx;
      font-weight: 550;

      .toolbar-map {
        background: url($baseMapImage) no-repeat center / 100% 100%;
        background-size: cover;
        width: 334rpx;
        height: 130rpx;

        image {
          width: 94rpx;
          height: 112rpx;
          margin: 11rpx 58rpx;
        }
      }

      .toolbar-text {
        margin: 50rpx 0rpx 0 77rpx;
      }

      .toolbar-item {
        width: 334rpx;
        height: 130rpx;
        margin-left: 23rpx;
        background-color: #fff;
        border-radius: 20rpx;

        .toolbar-img {
          text-align: center;
          width: 160rpx;

          image {
            width: 45rpx;
            height: 59rpx;
            margin-top: 17rpx;
          }

          .video {
            width: 69rpx;
            height: 44rpx;
            margin-top: 32rpx;
          }

          .toolbar-hr {
            width: 4rpx;
            height: 130rpx;
            margin-top: 0rpx;
          }
        }
      }
    }
  }
}
</style>
